package com.yc.cloud.wechat.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.yc.cloud.wechat.dto.QRCodeDto;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.val;
import lombok.extern.slf4j.Slf4j;

/**
 * @title: 微信小程序工具类
 * @Author JackGu
 * @Date: 2022/10/22 16:17
 * @Version 1.0
 */
@Slf4j
public class WxMiniProgramUtils {

    // 这里有点奇怪，为什么不是和下面一样的请求前缀
    private static final String BASE_URL = "https://api.weixin.qq.com";
    public static final String CGI_BIN_URL = BASE_URL + "/cgi-bin";
    public static final String SNS_URL = BASE_URL + "/sns";

    public static final String SUCCESS = "0";

    /***
     * description: 获取小程序AccessToken
     * 
     * @param
     * @return java.lang.String
     */
    public static String getAccessToken(String appid, String appKey) {
        val url = CGI_BIN_URL + "/token?grant_type=client_credential&appid=" + appid + "&secret=" + appKey;
        val result = HttpUtil.get(url);
        log.info("getAccessToken result \n" + result);
        return result;
    }

    // public static String getUserInfo(String accessToken, String openId) {
    // val url = BASE_URL + "/userinfo?access_token=" + accessToken + "&openid=" +
    // openId + "&lang=zh_CN";
    // val result = HttpUtil.get(url);
    // System.out.println("getUserInfo result \n" + result);
    // return result;
    // }

    public static String jscode2session(String jsCode, String appid, String appKey) {
        // 与微信
        val wechatLoginUrl = SNS_URL + "/jscode2session?appid=" + appid + "&secret=" + appKey + "&js_code=" + jsCode
                + "&grant_type=authorization_code";
        val result = HttpUtil.get(wechatLoginUrl);
        log.info("getOpenId result \n" + result);
        return result;
        // val jsCode2SessionResp = JSONUtil.toBean(result, JSCode2SessionResp.class);
        // if (StrUtil.isEmpty(jsCode2SessionResp.getErrcode())) {
        // return jsCode2SessionResp.getOpenid();
        // }
        // log.error("getOpenId failed,msg=" + jsCode2SessionResp.getErrmsg());
        // //Asserts.fail("获取OpenId失败,Msg=" + jsCode2SessionResp.getErrmsg());
        // return null;
    }


    /**
     * 
     * @param accessToken
     * @param qrCodeDto
     * @return
     */
    public static byte[] getUnlimitedQRCode(String accessToken, QRCodeDto qrCodeDto) {
        val url = BASE_URL + "/wxa/getwxacodeunlimit?access_token=" + accessToken;
        try {
            val response = HttpUtil.createPost(url).header("Content-Type", "application/json") // 设置请求头，指定发送 JSON 数据
                    .body(JSONUtil.toJsonStr(qrCodeDto)).execute();
            if (response.isOk()) {
                val data = response.bodyBytes();
                if (data == null) {
                    log.error("getUnlimitedQRCode result error--->数据内容为空");
                }
                return data;
            } else {
                log.error("getUnlimitedQRCode result error--->" + response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取微信小程序授权手机号
     * 
     * @param code        授权码
     * @param accessToken 接口调用凭证
     * @return 手机号
     */
    public static String getPhoneNumber(String code, String accessToken) {
        val url = BASE_URL + "/wxa/business/getuserphonenumber?access_token=" + accessToken;

        // 创建一个 Map 来表示 JSON 对象
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("code", code);

        // 使用 HttpRequest 设置请求头和请求体
        val result = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(requestBody)) // 将 Map 转换为 JSON 字符串
                .execute()
                .body();
        log.info("getPhoneNumber result \n" + result);
        return result;
    }

    // /***
    // * description: 获取临时票据
    // * @param accessToken 访问令牌
    // * @return java.lang.String
    // */
    // public static String getTicket(String accessToken) {
    // val url = BASE_URL + "/ticket/getticket?access_token=" + accessToken +
    // "&type=jsapi";
    // val result = HttpUtil.get(url);
    // val getTicketResp = JSONUtil.toBean(result, GetTicketResp.class);
    // if (SUCCESS.equals(String.valueOf(getTicketResp.getErrcode()))) {
    // return getTicketResp.getTicket();
    // }
    // return "";
    // }

    //

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        // ret.put("appid", appid);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);

    }

    public static void main(String[] args) {
        // val openid = getOpenId("0a1w5lGa1X6RDG0IsjGa1rlMfJ2w5lGG");
        // log.info(openid);
    }
}
